import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { BusinessException } from 'src/common/exceptions/business.exception'
import { Asset } from 'src/entity/Asset'
import { InStore } from 'src/entity/InStore'
import { Inventory } from 'src/entity/Inventory'
import { InventoryDetails } from 'src/entity/Inventory-details'
import { Task } from 'src/entity/Task'
import { Connection, IsNull, Repository } from 'typeorm'
import { v4 as uuidV4 } from 'uuid'

@Injectable()
export class InventoryService {
  constructor(
    @InjectRepository(Inventory)
    private inventoryRepository: Repository<Inventory>,
    private connection: Connection,
  ) { }

  async add(data) {
    const inventoryCode = 'I' + uuidV4()
    data.inventoryCode = inventoryCode
    data.inventoryType = '0'
    if (data.warehouseIdList.length) {
      // 数组变为字符串
      data.warehouseIds = (data.warehouseIdList as Array<any>).join(',')
    } else {
      data.warehouseIds = null
    }

    await this.connection.transaction(async (manager) => {
      const sqlQuery = (data.warehouseIdList as Array<any>).map((item) => {
        return {
          warehouseId: parseInt(item),
          isDelete: IsNull(),
          assetStatus: '1',
        }
      })
      const [assetSqlData, assetSqlDataCount] = await manager.findAndCount(
        Asset,
        {
          where: sqlQuery,
        },
      )
      // 盘点总数
      data.inventoryNumber = assetSqlDataCount
      // 新增盘点数据
      await manager.save(Inventory, data)
      // 插入盘点详情数据
      const inventoryDetailsDataList: Array<any> = assetSqlData.map((item) => {
        return {
          inventoryCode: data.inventoryCode,
          inventoryAssetCode: item.assetCode,
          inventoryAssetStatus: '0',
        }
      })
      manager.insert(InventoryDetails, inventoryDetailsDataList)
    })
    return {}
  }

  async del(id: number) {
    await this.connection.transaction(async (manager) => {
      const findInventory = await manager.findOne(Inventory, {
        where: {
          id,
          isDelete: IsNull(),
        },
      })
      // 删除详情
      manager.update(
        InventoryDetails,
        {
          inventoryCode: findInventory.inventoryCode,
        },
        {
          isDelete: true,
        },
      )
      // 删除盘点单
      manager.update(
        Inventory,
        {
          id,
        },
        {
          isDelete: true,
        },
      )
    })
    return {}
  }

  async update(data) {
    data.inventoryType = '0'
    if (data.warehouseIdList.length) {
      // 数组变为字符串
      data.warehouseIds = (data.warehouseIdList as Array<any>).join(',')
    } else {
      data.warehouseIds = null
    }
    if (data.warehouseIdList) delete data.warehouseIdList
    let sqlData
    await this.connection.transaction(async (manager) => {
      sqlData = await this.inventoryRepository.update(
        {
          id: data.id,
        },
        data,
      )
    })
    return sqlData
  }

  // 分页查询
  async getPageList({
    pageRequest: { pageIndex, pageSize },
    inventoryCode,
    inventoryName,
    inventoryPerson,
    inventoryType,
    orgId,
  }) {
    const sqlAllData = await this.inventoryRepository.find({
      where: {
        isDelete: IsNull(),
        receiveBranchId: orgId,
        inventoryCode: inventoryCode,
        inventoryName: inventoryName,
        inventoryPerson: inventoryPerson,
        inventoryType: inventoryType,
      },
    })
    const sqlData = await this.inventoryRepository.find({
      where: {
        isDelete: IsNull(),
        receiveBranchId: orgId,
        inventoryCode: inventoryCode,
        inventoryName: inventoryName,
        inventoryPerson: inventoryPerson,
        inventoryType: inventoryType,
      },
      skip: (pageIndex - 1) * pageSize,
      take: pageSize,
      withDeleted: false,
    })

    return {
      content: sqlData.map((item) => {
        return {
          ...item,
          inventoryPersonId: item.inventoryPersonId.toString(),
          warehouseIdList: item.warehouseIds.split(','),
        }
      }),
      total: sqlAllData.length,
    }
  }

  // 获取盘点详情 inventoryCode -> *
  async getDetailByCode(code) {
    let sqlData
    await this.connection.transaction(async (manager) => {
      sqlData = await manager.find(InventoryDetails, {
        where: {
          inventoryCode: code,
        },
      })
    })
    return sqlData
  }

  // 盘点详情分页列表
  async detailsPage({ pageRequest: { pageIndex, pageSize }, orgId, code }) {
    const resData = []
    let sqlAllData
    await this.connection.transaction(async (manager) => {
      // 总数
      sqlAllData = await manager.find(InventoryDetails, {
        where: {
          inventoryCode: code,
          isDelete: IsNull(),
        },
      })
      // 分页数据
      const sqlData = await manager.find(InventoryDetails, {
        where: {
          inventoryCode: code,
          isDelete: IsNull(),
        },
        skip: (pageIndex - 1) * pageSize,
        take: pageSize,
        withDeleted: false,
      })
      sqlData.forEach(async (item) => {
        const assetSqlData = await manager.findOne(Asset, {
          where: {
            assetCode: item.inventoryAssetCode,
          },
        })
        resData.push({
          ...item,
          ...assetSqlData,
          typeId: assetSqlData.typeId.toString(),
        })
      })
    })

    return {
      content: resData,
      total: sqlAllData.length,
    }
  }
  // 盘点
  async inventory(data) {
    await this.connection.transaction(async (manager) => {
      await manager.update(
        InventoryDetails,
        {
          inventoryCode: data.inventoryCode,
          inventoryAssetCode: data.inventoryAssetCode,
        },
        {
          inventoryAssetStatus: data.inventoryAssetStatus,
        },
      )
      // 盘盈
      if (data.inventoryAssetStatus === '2') {
        const assetCode = 'A' + uuidV4()
        const assetSqlData = await manager.save(Asset, {
          assetCode,
          typeId: parseInt(data.typeId),
          branchId: data.branchId,
          branchName: data.branchName,
          assetName: data.assetName,
          brand: data.brand,
          price: data.price,
          unit: data.unit,
          model: data.model,
          function: data.function,
          warehouseId: data.warehouseId,
          remark: '盘盈入库',
          assetStatus: '4',
        })
        // 新增盘盈入库
        await manager.insert(InStore, {
          inStoreName: data.title + '的盘盈入库',
          inStoreType: '4',
          inStoreDate: data.inStoreDate,
          inStoreNumber: 1,
          assetIds: assetSqlData.id.toString(),
          branchName: data.branchName,
          branchId: data.branchId,
          remark: data.remark,
        })
        // 盘亏
      } else if (data.inventoryAssetStatus === '1') {
        // 新增盘亏出库
        await manager.update(
          Asset,
          {
            assetCode: data.assetCode,
          },
          {
            assetStatus: '3',
            isDelete: true,
          },
        )
      }
      // 查询是否存在未盘点数据
      const inventoryDetailsCount = await manager.count(InventoryDetails, {
        where: {
          inventoryCode: data.inventoryCode,
          inventoryAssetStatus: '0',
        },
      })
      // 如果全部已经盘点了，设置盘点单状态为盘点完成
      if (!inventoryDetailsCount) {
        await manager.update(
          Inventory,
          {
            inventoryCode: data.inventoryCode,
          },
          {
            inventoryType: '1',
          },
        )
      }
    })
    return {}
  }

  // 整单完成
  async inventoryAll(data) {
    await this.connection.transaction(async (manager) => {
      // 未盘点资产设置为已盘点
      await manager.update(
        InventoryDetails,
        {
          inventoryCode: data.inventoryCode,
          inventoryAssetStatus: '0',
        },
        {
          inventoryAssetStatus: '3',
        },
      )
      // 设置盘点单状态为盘点完成
      await manager.update(
        Inventory,
        {
          inventoryCode: data.inventoryCode,
        },
        {
          inventoryType: '1',
        },
      )
    })

    return {}
  }
}
